662. 二叉树最大宽度
为保证权益,题目请参考 662. 二叉树最大宽度(From LeetCode).
解决方案1
Python
python
# 662. 二叉树最大宽度
# https://leetcode.cn/problems/maximum-width-of-binary-tree/
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
depth_left = dict()
depth_right = dict()
def dfs(root: Optional[TreeNode], depth: int, id: int):
if root:
if depth not in depth_left:
depth_left[depth] = id
else:
depth_left[depth] = min(depth_left[depth], id)
if depth not in depth_right:
depth_right[depth] = id
else:
depth_right[depth] = max(depth_right[depth], id)
dfs(root.left, depth + 1, 2 * id + 1)
dfs(root.right, depth + 1, 2 * id + 2)
dfs(root, 0, 0)
ans = 1
for k, v in depth_left.items():
ans = max(ans, depth_right[k] - depth_left[k] + 1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41